<?php

/**
 * 导出excel表格
 */
function exportExcel($data, $filename)
{
    $xlsTitle = iconv('utf-8', 'gb2312', $filename); //文件名称
    //$fileName = $filename . "-" . date('YmdHis'); //or $xlsTitle 文件名称可根据

    vendor("PHPExcel.PHPExcel");
    $objPHPExcel = new \PHPExcel();
    $objPHPExcel->setActiveSheetIndex(0);

    $dateExcel = $objPHPExcel->getActiveSheet();

    $dateExcel->getDefaultStyle()->getFont()->setName('微软雅黑');
    $dateExcel->getDefaultStyle()->getFont()->setSize(12);   //字体大小
    $dateExcel->getStyle('1')->getFont()->setBold(true);    //第一行是否加粗
    $dateExcel->getStyle('1')->getFont()->setSize(13);         //第一行字体大小

    $dateExcel->getStyle('1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //水平居中

    // 设置行高度
    $dateExcel->getDefaultRowDimension()->setRowHeight(20); //设置默认行高
    $dateExcel->getRowDimension('1')->setRowHeight(30);    //第一行行高

    $rows = count($data);
    for ($i = 0; $i < count($data); $i++) {
        $row = $i + 1;
        $key = ord("A"); //A--65
        $key2 = ord("@"); //@--64
        foreach ($data[$i] as $d) {
            if ($key > ord("Z")) {
                $key2 += 1;
                $key = ord("A");
                $col = chr($key2) . chr($key); //超过26个字母时才会启用
            } else {
                if ($key2 >= ord("A")) {
                    $col = chr($key2) . chr($key); //超过26个字母时才会启用
                } else {
                    $col = chr($key);
                }
            }
            $dateExcel->setCellValue($col . $row, $d);
            $key++;
        }
    }
    //边框样式
    $styleArray = array(
        'borders' => array(
            'allborders' => array(
                //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的
                'style' => \PHPExcel_Style_Border::BORDER_THIN,
                //细边框
                'color' => array('argb' => '#000'),
            ),
        ),
    );
    $dateExcel->getStyle('A1:' . $col . $rows)->applyFromArray($styleArray);
    $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);

    ob_end_clean(); //!!!!!!!清除缓冲区,避免乱码

    header('pragma:public');

    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');

    header("Content-Disposition:attachment;filename=$filename.xls");

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

    $objWriter->save('php://output');
}
